package com.base.vistter.iframe.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.base.vistter.iframe.entity.SysNotice;
import com.base.vistter.iframe.entity.SysNoticeUser;
import com.base.vistter.iframe.entity.SysUser;
import com.base.vistter.iframe.exception.IframeException;
import com.base.vistter.iframe.mapper.SysNoticeMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class SysNoticeService extends BaseService<SysNoticeMapper, SysNotice> {

    @Resource(name = "sysUserService")
    private SysUserService sysUserService;
    @Resource(name = "sysTeamUserService")
    private SysTeamUserService sysTeamUserService;
    @Resource(name = "sysNoticeUserService")
    private SysNoticeUserService sysNoticeUserService;

    @Transactional(propagation = Propagation.REQUIRED)
    public boolean save(SysNotice entity) throws IframeException {
        SysUser user = sysUserService.getCurrentUser();
        entity.setCreatorName(user.getUsername());

        return super.save(entity);
    }

    @Transactional(readOnly = true)
    public SysNotice getSysNoticeById(Integer id) throws IframeException{
        SysNotice sysNotice = super.getById(id);
        sysNotice.setViewCount(sysNoticeUserService.view(id));
        return sysNotice;
    }

    @Transactional(readOnly = true)
    public List<SysNotice> unreadNotice() throws IframeException {
        List<SysNoticeUser> list = sysNoticeUserService.selectUnread();
        if (list != null && !list.isEmpty()) {
            List<Integer> ids = list.stream().map(SysNoticeUser::getSysNoticeId).collect(Collectors.toList());
            LambdaQueryWrapper<SysNotice> lambdaQueryWrapper = new LambdaQueryWrapper<SysNotice>();
            lambdaQueryWrapper.in(SysNotice::getId, ids).eq(SysNotice::getStatus, 0);
            lambdaQueryWrapper.and(wrapper -> {
                wrapper.isNull(SysNotice::getDeadline).or().gt(SysNotice::getDeadline, new Date());
            });
            lambdaQueryWrapper.orderByDesc(SysNotice::getCreateDate);
            return super.selectList(lambdaQueryWrapper);
        } else {
            return null;
        }
    }

    @Transactional(readOnly = true)
    public SysNotice latest() throws IframeException {
        SysNoticeUser sysNoticeUser = sysNoticeUserService.latest();
        if (sysNoticeUser != null) {
            SysNotice sysNotice = super.getById(sysNoticeUser.getSysNoticeId());
            sysNotice.setIsRead(sysNoticeUser.getStatus());
            return sysNotice;
        }
        return null;
    }

}
